package com.dark.cms.base.web;

import com.dark.cms.base.cache.BaseCache;
import com.dark.cms.base.dao.MyBatisDao;
import com.dark.cms.base.dto.ResDTO;
import com.dark.cms.base.exception.AppException;
import com.dark.cms.base.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 基础控制器
 * Created by Devil on 2015/1/24.
 */
public abstract class BaseController {

    @Autowired
    private BaseService baseService;

    /**
     * 获取数据库操作对象
     * @return
     */
    protected MyBatisDao getDao(){
        return this.baseService.getDao();
    }

    /**
     * 获取视图路径
     * @param name
     * @param type
     *      1 后台根目录
     * @return
     */
    protected String viewName(String name, int type){
        switch (type){
            case 1: //后台根目录
                return BaseCache.MANAGE_PREFIX + name;
            default:
                throw new AppException("未知的视图类型");
        }
    }

    /**
     * 异常处理器
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler
    private @ResponseBody Map exception(HttpServletRequest request, Exception e){
//        if(isAjaxSubmit(request)){
//            ResData res = new ResData();
//            res.setCode(ResData.CODETYPE.B_FAILURE);
//            res.setMsg(e.getMessage());
//        }else{
//
//        }
//        e.printStackTrace();
//        System.out.println(e.getMessage());
        System.out.println("报错了");
        ResDTO res = new ResDTO();
        res.setCode(ResDTO.CODETYPE.B_FAILURE);
        res.setMsg(e.getMessage());
        Map map = new HashMap();
        map.put("code", "00");
        map.put("msg", e.getMessage());
        return map;
    }

    /**
     * 判断是否是ajax提交
     * @param request
     * @return
     */
    protected boolean isAjaxSubmit(HttpServletRequest request){
      return "XMLHttpRequest".equals(request.getHeader("x-requested-with"));
    }
}
